﻿CREATE PROCEDURE [dbo].[yaf_topic_updatelastpost](
                @ForumID INT  = NULL,
                @TopicID INT  = NULL)
AS
    BEGIN
        IF @TopicID IS NOT NULL
        UPDATE yaf_Topic
        SET    LastPosted = (SELECT   TOP 1 x.Posted
                             FROM     yaf_Message x
                             WHERE    x.TopicID = yaf_Topic.TopicID
                             AND (x.Flags & 24) = 16
                             ORDER BY Posted DESC),
               LastMessageID = (SELECT   TOP 1 x.MessageID
                                FROM     yaf_Message x
                                WHERE    x.TopicID = yaf_Topic.TopicID
                                AND (x.Flags & 24) = 16
                                ORDER BY Posted DESC),
               LastUserID = (SELECT   TOP 1 x.UserID
                             FROM     yaf_Message x
                             WHERE    x.TopicID = yaf_Topic.TopicID
                             AND (x.Flags & 24) = 16
                             ORDER BY Posted DESC),
               LastUserName = (SELECT   TOP 1 x.UserName
                               FROM     yaf_Message x
                               WHERE    x.TopicID = yaf_Topic.TopicID
                               AND (x.Flags & 24) = 16
                               ORDER BY Posted DESC)
        WHERE  TopicID = @TopicID
        ELSE
        UPDATE yaf_Topic
        SET    LastPosted = (SELECT   TOP 1 x.Posted
                             FROM     yaf_Message x
                             WHERE    x.TopicID = yaf_Topic.TopicID
                             AND (x.Flags & 24) = 16
                             ORDER BY Posted DESC),
               LastMessageID = (SELECT   TOP 1 x.MessageID
                                FROM     yaf_Message x
                                WHERE    x.TopicID = yaf_Topic.TopicID
                                AND (x.Flags & 24) = 16
                                ORDER BY Posted DESC),
               LastUserID = (SELECT   TOP 1 x.UserID
                             FROM     yaf_Message x
                             WHERE    x.TopicID = yaf_Topic.TopicID
                             AND (x.Flags & 24) = 16
                             ORDER BY Posted DESC),
               LastUserName = (SELECT   TOP 1 x.UserName
                               FROM     yaf_Message x
                               WHERE    x.TopicID = yaf_Topic.TopicID
                               AND (x.Flags & 24) = 16
                               ORDER BY Posted DESC)
        WHERE  TopicMovedID IS NULL 
        AND (@ForumID IS NULL 
              OR ForumID = @ForumID)
            
        EXEC yaf_forum_updatelastpost
             @ForumID
    END


